You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules:
The chosen integers have to be in the range [1, n].
Each integer can be chosen at most once.
The chosen integers should not be in the array banned.
The sum of the chosen integers should not exceed maxSum.
Return the maximum number of integers you can choose following the mentioned rules.
題目給咱一個整數陣列banned和兩個整數n、maxSum。
我們要從[1, n]範圍內選擇一些數,選擇時必須遵守以下規則:
我的解題思路:
class Solution {
public int maxCount(int[] banned, int n, int maxSum) {
int sum = 0;
int count = 0;
// 從1開始遍歷到n
for (int i = 1; i <= n; i++) {
boolean isBanned = false;
for (int j = 0; j < banned.length; j++) {
if (banned[j] == i) {
isBanned = true;
break; //!!!
}
}
// 如果當前數字被ban就跳過
if (isBanned) {
continue;
}
// 總和不超過maxSum,則選擇該數字
if (sum + i <= maxSum) {
sum += i;
count++;
} else {
// 總和超過
break;
}
}
return count;
}
}
結束這回合!但我途中continue和break有點用混了,花了意外多時間,哈哈。